<?php

class User 
{

	public function add()
	{
		$user = $_POST;

		$user['create_time'] = time();

		$user['password'] = md5($user['password']);

		unset($user['repassword']);

		$db = new Db('user');

		$db->insert($user);
		
		$this->web_ok();
	}

	public function web_ok()
	{
		header("Location:./index.php");
	}
	
	public function register()
	{
		include './template/register.html';
	}

	public function check_phone($data)
	{
		$preg = "/^1\d{10}$/";

		$c = preg_match($preg,$data);

		if(!$c){
			$this->error('手机格式不正确');
		}

		$db = new Db('user');

		$db->where("phone='{$data}'");

		$user = $db->select();

		if($user){
			throw new Exception("手机已存在", 1);
		}

		$this->ok('可用');
	}

	public function check_username($data)
	{
		$preg = "/^[a-zA-Z]\w{5,7}$/";

		$c = preg_match($preg,$data);

		if(!$c){

			throw new Exception("不能数字，下划线开头，6-8位", 1);
			// $this->error('不能数字，下划线开头，6-8位');
		}

		$db = new Db('user');

		$db->where("username='{$data}'");

		$user = $db->select();

		if($user){
			throw new Exception("用户名已存在", 1);
		}

		$this->ok('可用');
	}

	public function error($msg)
	{
		exit(json_encode(['error'=>1,'info'=>$msg]));
	}

	public function ok($msg)
	{
		exit(json_encode(['error'=>0,'info'=>$msg]));
	}

	public function check_email($data)
	{
		$preg = "/^\w+@([\da-z]{1,2}|[\da-z][\da-z-]+[\da-z])(\.[a-z]{2,})+$/";

		$c = preg_match($preg,$data);

		if(!$c){
			$this->error('邮箱格式不正确');
		}

		$db = new Db('user');

		$db->where("username='{$data}'");

		$user = $db->select();

		if($user){
			throw new Exception("邮箱已存在", 1);
		}

		$this->ok('可用');
	}
	public function check_password($data)
	{
		$preg = "/^\w{6,16}$/";

		$c = preg_match($preg,$data);

		if(!$c){
			$this->error('密码长度6-16位');
		}

		$this->ok('可用');
	}

	public function check_repassword($data)
	{
		$preg = "/^\w{6,16}$/";

		$c = preg_match($preg,$data);

		if(!$c){
			$this->error('密码长度6-16位');
		}

		if($data!=$_POST['password']){
			$this->error('两次密码不一样');
		}

		$this->ok('可用');
	}

	public function register_ajax()
	{

		$name = "check_".$_POST['name'];

		$data = $_POST['data'];

		try{
			$this->$name($data);
		}catch (Exception $e) {
			$this->error($e->getMessage());
		}
	}

	public function login()
	{
		$username = $_POST['username'];

		$password = md5($_POST['password']);


		$db = new Db('user');

		$db->where("username='{$username}' and password='{$password}'");

		$user = $db->select();

		if($user){
			$_SESSION['user'] = current($user);
			$this->ok('登录成功');
		}
		$this->error('用户名或者密码不正确');
	}

	public function loginout()
	{
		session_unset();

		$this->web_ok();
	}

	public function is_login()
	{
		# code...
	}
}